using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

using System.Security.Claims;

using WXWorkSvc.Common.Data;

namespace WXWorkSvc.Common.Pages.Logger;

public class ListModel : PageModel
{
    const int PageSize = 50;
    private readonly SqlServerLoggerProcessor svc;
    public ListModel(SqlServerLoggerProcessor service) => svc = service;

    public bool HasNext { get; set; }
    public bool HasPrevious { get; set; }

    [BindProperty(SupportsGet = true)]
    public string? SearchText { get; set; }
    [BindProperty(SupportsGet = true)]
    public LogLevel Level { get; set; }
    public List<VLogger> Items { get; set; } = new();
    public async Task OnGetAsync(long id=0)
    {
        List<SqlParameter> parameters = new List<SqlParameter>();
        StringBuilder sbSql = new StringBuilder();

        sbSql.Append($"SELECT top {PageSize + 1} Id,[Dt],[Name],[LogLevel],[ShortMsg] FROM [Loggers] where appid=@AppId");
        parameters.Add(new SqlParameter("@AppId", svc.AppId));
        if (id > 0)
            sbSql.Append($" and id>{id}");
        else if (id < 0)
            sbSql.Append($" and id<{-id}");

        if (Level != LogLevel.Trace)
            sbSql.Append($" and loglevel>={(int)Level} ");
        if (!string.IsNullOrEmpty(SearchText))
        {
            sbSql.Append(" and contains((name, msg),@SearchText)");
            parameters.Add(new SqlParameter("@SearchText", SearchText));
        }
        if (id < 0)
            sbSql.Append(" order by id desc");
        else
            sbSql.Append(" order by id");


        using var cn = new SqlConnection(svc.ConnectionString);
        var cmd = cn.CreateCommand();
        cmd.Parameters.AddRange(parameters.ToArray());
        cmd.CommandText = sbSql.ToString();
        await cn.OpenAsync();
        using var dr = await cmd.ExecuteReaderAsync();
        while (await dr.ReadAsync())
            Items.Add(new VLogger(dr.GetInt64(0), dr.GetDateTime(1), dr.GetString(2), dr.GetInt32(3), dr.GetString(4)));
        await dr.CloseAsync();
        await cn.CloseAsync();

        if (id >= 0)
        {
            HasPrevious = id > 0;
            HasNext = Items.Count == PageSize + 1;
            if (HasNext)
                Items.RemoveAt(PageSize);

        }
        else
        {
            HasPrevious = Items.Count == PageSize + 1;
            HasNext = true;
            if (HasPrevious)
                Items.RemoveAt(PageSize);
            Items.Reverse();

        }
    }

}
